package com.keyword.springbootkeyword.Java;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Hanson
 * @date 2022/10/18 9:49
 */
@Slf4j
public class Automic {

    /**
     * AtomicInteger
     */
    @Test
    public void atomicInteger(){
        AtomicInteger atomicInteger = new AtomicInteger(1);
        atomicInteger.get(); //获取当前值
        atomicInteger.set(999); //设置当前值
        log.info(atomicInteger.get()+"");
    }

    /**
     * atomicInteger的值与expectedValue相比较，如果不相等，则返回false,
     * atomicInteger原有值保持不变；如果两者相等，则返回true,atomicInteger的值更新为newValue
     */
    @Test
    public void compareAndSet(){
        AtomicInteger atomicInteger = new AtomicInteger(0);
        System.out.println(atomicInteger.get());

        int expectedValue = 123;
        int newValue      = 234;
        Boolean b =atomicInteger.compareAndSet(expectedValue, newValue);
        System.out.println(b);
        System.out.println(atomicInteger);

        System.out.println("--------------------");

        AtomicInteger atomicInteger2 = new AtomicInteger(123);
        System.out.println(atomicInteger2.get());

        int expectedValue2 = 123;
        int newValue2      = 234;
        Boolean b2 =atomicInteger.compareAndSet(expectedValue2, newValue2);
        System.out.println(b2);
        System.out.println(atomicInteger2);

    }


}
